import axios from 'axios'
import { Message } from 'element-ui'
// import store from '../store'
// import { getToken } from '@/utils/auth'

// 配置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.timeout = 5000
// axios.defaults.baseURL = ''
// // 创建axios实例
// const service = axios.create({
//   baseURL: process.env.BASE_URL, // api的base_url
//   timeout: 15000                 // 请求超时时间
// })

// // request拦截器
axios.interceptors.request.use(config => {
  // if (store.getters.token) {
  //   config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  // }
  config.headers['Authorization'] = 'Authorization'
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
axios.interceptors.response.use(
  response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
    const res = response.data
    // 根据业务自定义
    // if (res.code !== 0) {
    //   debugger
    //   console.log(true)
    // } else {
    //   return response.data
    // }
    return res
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
function fetch (obj) {
  return new Promise((resolve, reject) => {
    if (obj.method === 'get') {
      axios.get(obj.url, {params: obj.params}).then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
    } else if (obj.method === 'post') {
      axios.post(obj.url, obj.params).then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
    }
  })
}
export default fetch
